package com.obggtc.picture.controller;

import com.obggtc.picture.common.R;
import com.obggtc.picture.dto.LoginRequest;
import com.obggtc.picture.dto.LoginResponse;
import com.obggtc.picture.service.UserService;
import com.obggtc.picture.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户登录
     * @param loginRequest 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public R<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        // 验证用户名和密码
        boolean isValid = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
        
        if (!isValid) {
            return R.failed("用户名或密码错误");
        }
        
        // 生成JWT Token
        String token = jwtUtils.generateToken(loginRequest.getUsername());
        
        // 构建响应
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUsername(loginRequest.getUsername());
        response.setExpiresIn(24 * 60 * 60 * 1000L); // 24小时
        
        return R.ok(response, "登录成功");
    }
} 